/**
 * 
 */
package com.ponxu.mb.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.ponxu.db.SqlBuilder;
import com.ponxu.db.SqlRunner;
import com.ponxu.db.wrap.RowWrapper;
import com.ponxu.mb.Global;
import com.ponxu.mb.db.ConnectionManager;
import com.ponxu.mb.model.User;
import com.ponxu.utils.Lang;

/**
 * 作者
 * 
 * @author xwz
 * 
 */
public class UserService {
	public static String USER_TABLE = Global.read("DB_TABLE_PREFIX") + "user";

	// 全字段查询
	private static String fullCols = "*";
	private static RowWrapper<User> fullRowWrapper = new RowWrapper<User>() {
		public User wrap(ResultSet rs) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setLogin(rs.getString("login"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setEmail(rs.getString("email"));
			user.setRegisteredTime(rs.getDate("registered"));
			user.setStatus(rs.getString("status"));
			return user;
		}
	};

	public static User getById(int id) {
		SqlBuilder.SELECT(fullCols);
		SqlBuilder.FROM(USER_TABLE);
		SqlBuilder.WHERE("id=?");
		return new SqlRunner(ConnectionManager.get()).selectOne(
				SqlBuilder.SQL(), fullRowWrapper, id);
	}

	public static User getByLogin(String login) {
		SqlBuilder.SELECT(fullCols);
		SqlBuilder.FROM(USER_TABLE);
		SqlBuilder.WHERE("status='activated'");
		SqlBuilder.WHERE("login=?");
		return new SqlRunner(ConnectionManager.get()).selectOne(
				SqlBuilder.SQL(), fullRowWrapper, login);
	}

	public static Object attempLogin(String login, String password) {
		User user = getByLogin(login);
		if (user == null) {
			return "无此用户!";
		}

		if (!user.getPassword().equalsIgnoreCase(password)) {
			return "密码错误!";
		}

		return user;
	}

	public static int update(User user) {
		SqlBuilder.UPDATE(USER_TABLE);
		SqlBuilder.SET("login=?,name=?,password=?,email=?,status=?");
		SqlBuilder.WHERE("id=?");
		return new SqlRunner(ConnectionManager.get()).execute(SqlBuilder.SQL(),
				user.getLogin(), user.getName(), user.getPassword(),
				user.getEmail(), user.getStatus(), user.getId());
	}

}
